/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package Mobilin_mobile_pack;

import javax.microedition.midlet.*;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.List;
import javax.microedition.lcdui.Choice;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.TextField;
import javax.microedition.lcdui.StringItem;
import javax.microedition.lcdui.DateField;
import javax.microedition.lcdui.ChoiceGroup;
import javax.wireless.messaging.*;
import javax.microedition.io.Connector;
import java.io.*;
import javax.microedition.rms.*;
import java.util.*;

/**
 * @author Jun
 */
public class Mobilin extends MIDlet implements CommandListener, MessageListener {

    private Display display;
    private Command goCommand, quitCommand, selectCommand, sendCommand, backCommand, replyCommand, cancelCommand;
    //private Canvas logoCanvas;
    private Image logoImage, requestRFImage, viewRFImage, settingsImage;
    private Alert logoAlert;
    private List actionList;
    private Form requestForm, referralForm, rcvForm, settingsForm;
    private TextField caseNoTF, rcvrNameTF, rcvrAdTF, rcvrTelFaxTF, 
                rcvrNameAndDesignationTF, serverNumTF, pinTF, smearExams[];
    private StringItem pinSI, instructionSI, referrerNameSI, referrerAdSI, referrerTelFaxSI,
        patientNameSI, ageSI, sexSI, patientAdSI, newPatientAdSI, caseNoSI,
        treatmentStartSI, categorySI, classSI, typeSI, remarksSI, nameAndDesignationSI,
        dateReferredSI, smearResultSI, siteSI;
    private StringItem rcvPatientNameSI, rcvAgeSI, rcvSexSI, rcvrCaseNoSI, tcserSI, smearsSI[];
    private DateField rcvdDF;
    private ChoiceGroup drugsCG[];
    private MessageConnection serverConn;
    private String msgReceived, rsStr[], drugsStr[] = {"H", "R", "Z", "E", "S"}, drugsStr2,
                classesStr[] = {"", "Pulmonary", "Extra-Pulmonary"}, typesStr[] = {"", "New", "Relapse", "Failure", "Return After Default", "Transfer In", "Other"},
                smearsStr[] = {"", "Positive", "Negative", "not done", "unknown"},
                referralStr="", drugsBitsStr[], smearResultsStr, dataStr;
    private RecordStore rs = null;
    private int drugsInt[], classInt;
    private boolean rcvd;
    private byte data[];
    private Vector referralSMSV;
    private Timer timer;

    public Mobilin() {

        try {
            rs = RecordStore.openRecordStore("mobilinRS", true);
            if (rs.getNumRecords() == 0 ) {
                data = (new String("%")).getBytes();
                for (int i=0; i<40; i++)
                    rs.addRecord(data, 0, data.length);
            }
        } catch(RecordStoreException rse) {}

        goCommand = new Command("Go", Command.SCREEN, 1);
        quitCommand = new Command("Quit", Command.EXIT, 1);
        selectCommand = new Command("Select", Command.ITEM, 1);
        sendCommand = new Command("Send", Command.OK, 1);
        backCommand = new Command("Back", Command.BACK, 1);
        replyCommand = new Command("Reply", Command.SCREEN, 1);
        cancelCommand = new Command("Cancel", Command.CANCEL, 1);
        
        try {
            logoImage = Image.createImage("/img/logo.png");
            requestRFImage = Image.createImage("/img/request.png");
            viewRFImage = Image.createImage("/img/view.png");
            settingsImage = Image.createImage("/img/settings.png");
        } catch (Exception e) {}
        logoAlert = new Alert("", "Welcome to MOBILIN!", logoImage, AlertType.INFO);
        //logoCanvas.repaint

        actionList = new List("Select Action", Choice.IMPLICIT);
        actionList.append("Request Referral Form", requestRFImage);
        actionList.append("View Referral Form", viewRFImage);
        actionList.append("Settings", settingsImage);
        actionList.setSelectCommand(selectCommand);
        //actionList.addCommand(selectCommand);
        actionList.addCommand(quitCommand);
        actionList.setCommandListener(this);

        requestForm = new Form("Request Referral Form");
        caseNoTF = new TextField("TB Case No:", "", 8, TextField.NUMERIC);
      try {
        pinSI = new StringItem("PIN:", getData(2));
      } catch(Exception e) {e.printStackTrace();}
        //} catch (InvalidRecordIDException irie) {
        //} catch (RecordStoreException rse) {}
        requestForm.append(caseNoTF);
        requestForm.append(pinSI);
        requestForm.addCommand(sendCommand);
        //requestForm.addCommand(new Command("Get", Command.SCREEN, 1));
        requestForm.addCommand(backCommand);
        requestForm.addCommand(quitCommand);
        requestForm.setCommandListener(this);

       try {
        referralForm = new Form("NTP Referral / Transfer Form");
        instructionSI = new StringItem("Pls complete treatment.", "");
        referralForm.append(instructionSI);
        referrerNameSI = new StringItem("Full Name of Referring Unit:", getData(4));
        referralForm.append(referrerNameSI);
        referrerAdSI = new StringItem("Full Address of Referring Unit:", getData(5));
        referralForm.append(referrerAdSI);
        referrerTelFaxSI = new StringItem("Telephone / Fax number of Referring Unit:", getData(6));
        referralForm.append(referrerTelFaxSI);
        patientNameSI = new StringItem("Name of the Patient:", getData(7));
        referralForm.append(patientNameSI);
        ageSI = new StringItem("Age:", getData(8));
        referralForm.append(ageSI);
        sexSI = new StringItem("Sex:", getData(9));
        referralForm.append(sexSI);
        patientAdSI = new StringItem("Address of the Patient:", getData(10));
        referralForm.append(patientAdSI);
        newPatientAdSI = new StringItem("New Address of the Patient:", getData(11));
        referralForm.append(newPatientAdSI);
        caseNoSI = new StringItem("TB Case Number:", getData(12));
        referralForm.append(caseNoSI);
        treatmentStartSI = new StringItem("Date Treatment Started:", getData(13));
        referralForm.append(treatmentStartSI);
        categorySI = new StringItem("Category:", getData(14));//
        referralForm.append(categorySI);
        dataStr = getData(15);
        if (dataStr.equals(""))
            classSI = new StringItem("Classification of the Patient:", "");
        else
            classSI = new StringItem("Classification of the Patient:", classesStr[Integer.parseInt(dataStr)]);
        referralForm.append(classSI);
        dataStr = getData(16);
        if (dataStr.equals(""))
            typeSI = new StringItem("Type of the Patient:", "");
        else
            typeSI = new StringItem("Type of the Patient:", typesStr[Integer.parseInt(dataStr)]);
        referralForm.append(typeSI);
        dataStr = getData(17);
        if (dataStr.equals(""))
            smearResultSI = new StringItem("Smear Examination result on diagnosis:", "");
        else
            smearResultSI = new StringItem("Smear Examination result on diagnosis:", smearsStr[Integer.parseInt(dataStr)]);
        referralForm.append(smearResultSI);
        tcserSI = new StringItem("Treatment Course and Smear Examination results", null);
        referralForm.append(tcserSI);
        drugsCG = new ChoiceGroup[10];
        smearsSI = new StringItem[10];
        drugsBitsStr = new String[5];
        for (int i=0; i<5; i++)
           drugsBitsStr[i] = getData(18+i);
        smearResultsStr = getData(23);
        for (int i=0; i<10; i++) {
           drugsCG[i] = new ChoiceGroup("Month "+(i+1), Choice.MULTIPLE, drugsStr, null);
           for (int j=0; j<5; j++)
               if (!drugsBitsStr[j].equals("") && drugsBitsStr[j].charAt(i) == '1')
                   drugsCG[i].setSelectedIndex(j, true);
           if (!smearResultsStr.equals(""))
               smearsSI[i] = new StringItem("Smear", String.valueOf(smearResultsStr.charAt(i)));
        }
        remarksSI = new StringItem("Remarks:", getData(38));
        referralForm.append(remarksSI);
        nameAndDesignationSI = new StringItem("Printed Name / Signature & Designation:", getData(39));
        referralForm.append(nameAndDesignationSI);
        dateReferredSI = new StringItem("Date Referred:", getData(40));
        referralForm.addCommand(replyCommand);
        referralForm.addCommand(sendCommand);
        referralForm.addCommand(backCommand);
        referralForm.addCommand(quitCommand);
        referralForm.setCommandListener(this);

        rcvForm = new Form("Receive Form");
        rcvrNameTF = new TextField("Name of Receiving Unit:", "", 35, TextField.ANY);
        rcvForm.append(rcvrNameTF);
        rcvdDF = new DateField("Date Received:", DateField.DATE);
        rcvForm.append(rcvdDF);
        rcvrAdTF = new TextField("Full Address of Receiving Unit:", "", 55, TextField.ANY);
        rcvForm.append(rcvrAdTF);
        rcvrTelFaxTF = new TextField("Telephone / Fax number of Receiving Unit:", "", 7, TextField.NUMERIC);
        rcvForm.append(rcvrTelFaxTF);
        rcvPatientNameSI = new StringItem("Name of the Patient:", getData(7));
        rcvForm.append(rcvPatientNameSI);
        rcvAgeSI = new StringItem("Age:", getData(8));
        rcvForm.append(rcvAgeSI);
        rcvSexSI = new StringItem("Sex:", getData(9));
        rcvForm.append(rcvSexSI);
        rcvrCaseNoSI = new StringItem("TB Case Number at Receiving Unit:", "");
        rcvForm.append(rcvrCaseNoSI);
        rcvrNameAndDesignationTF = new TextField("Printed Name / Signature & Designation:", "", 25, TextField.ANY);
        rcvForm.append(rcvrNameAndDesignationTF);
        rcvForm.addCommand(sendCommand);
        rcvForm.addCommand(cancelCommand);
        rcvForm.addCommand(quitCommand);
        rcvForm.setCommandListener(this);

        settingsForm = new Form("Settings");
        serverNumTF = new TextField("Server Number:", "", 13, TextField.NUMERIC);
        settingsForm.append(serverNumTF);
        pinTF = new TextField("PIN:", "", 10, TextField.PASSWORD);
        settingsForm.append(pinTF);
        settingsForm.addCommand(new Command("Save", Command.OK, 1));
        settingsForm.addCommand(backCommand);
        settingsForm.addCommand(quitCommand);
        settingsForm.setCommandListener(this);
        
        //rsStr = RecordStore.listRecordStores();
        referralSMSV = new Vector(2);

        //referralStr = "GK Payatas%33 Rd 5, GK Payatas, Q.C.%4537162%Reynaldo Manguni%20%M%14 Rd 8, GK Payatas, Q.C.%63 Rd 9, GK Negros, Bacolod City%11031989%Nov 28 09%II%0%3%2%1010101010%0101010101%1010101010%0101010101%1010101010%+-+-+-+-+-%transferred for continuation of treatment%Mel Navarro, HW%Feb 28 09";//
        //addToRS();//
       } catch(Exception e) {e.printStackTrace();}
        
    }

    public void commandAction(Command com, Displayable dis) {
        String rcvStr, comLabel = com.getLabel();
        /*if (comLabel.equals("Go")) {
            if (dis.equals(logo))
                display.setCurrent(actionList);
        }*/
        if (comLabel.equals("Quit"))
            destroyApp(false);
        else if (comLabel.equals("Select")) {
        //else if (com.equals(List.SELECT_COMMAND)) {
            if (dis.equals(actionList))
                switch (actionList.getSelectedIndex()) {
                    case 0:
                        display.setCurrent(requestForm);
                        break;
                    case 1:
                        display.setCurrent(referralForm);
                        break;
                    case 2:
                        display.setCurrent(settingsForm);
                        break;
                }
        }
        else if (comLabel.equals("Send")) {
            if (dis.equals(requestForm)) {
                try {
                    data = caseNoTF.getString().getBytes();
                    rs.setRecord(3, data, 0, data.length);
                } catch(RecordStoreNotOpenException rsnoe) {
                } catch(RecordStoreException rse) {}
                send(caseNoTF.getString()+"%"+pinSI.getText());
                timer = new Timer();
                timer.run();
                display.setCurrent(actionList);
            }
            else if (dis.equals(referralForm));
            else if (dis.equals(rcvForm)) {
                rcvd = false;
                rcvStr = rcvrNameTF.getString()+"%"+rcvdDF.getDate().toString()+"%"+
                        rcvrAdTF.getString()+"%"+rcvrTelFaxTF.getString()+"%"+
                        rcvPatientNameSI.getText()+"%"+rcvAgeSI.getText()+"%"+
                        rcvSexSI.getText()+"%"+rcvrCaseNoSI.getText()+"%"+rcvrNameAndDesignationTF.getString();
                send(rcvStr);
            }
        }
        else if (comLabel.equals("Back")) {
            if (dis.equals(requestForm) || dis.equals(referralForm) || dis.equals(settingsForm))
                display.setCurrent(actionList);
            else if (dis.equals(rcvForm))
                display.setCurrent(referralForm);
        }
        else if (comLabel.equals("Reply"))
            display.setCurrent(rcvForm);
        else if (comLabel.equals("Cancel"))
            display.setCurrent(referralForm);
        else if (comLabel.equals("Save")) {
            try {
                data = serverNumTF.getString().getBytes();
                rs.setRecord(1, data, 0, data.length);
                data = pinTF.getString().getBytes();
                rs.setRecord(2, data, 0, data.length);
            } catch(RecordStoreNotOpenException rsnoe) {
            } catch(RecordStoreException rse) {}
            display.setCurrent(actionList);
            pinSI.setText(pinTF.getString());
        }
            
    }

    public void startApp() {
        display = Display.getDisplay(this);
        display.setCurrent(logoAlert, actionList);//logoCanvas

        try {
            serverConn = (MessageConnection)Connector.open("sms://:5000");
            serverConn.setMessageListener(this);
        } catch (IOException io) {
            System.out.println("Server connection could not be obtained");
            io.printStackTrace();
        }
    }

    public void pauseApp() {
    }

    public void destroyApp(boolean unconditional) {
        notifyDestroyed();
    }

    public void notifyIncomingMessage(MessageConnection conn) {
        Message msg = null;
        try {
            msg = conn.receive();
        } catch (Exception e) {
            System.out.println("processMessage.receive " + e);
        }
        if (msg instanceof TextMessage) {
            TextMessage tmsg = (TextMessage)msg;
    		msgReceived = tmsg.getPayloadText();
            if (!msgReceived.startsWith("ACK")) {
                //send("ACK"+msgReceived.substring(0, 2));
                referralSMSV.insertElementAt(msgReceived.substring(2), Integer.parseInt(msgReceived.substring(0, 2)));
            }
            else
                rcvd = true;
        }
        else {
            if (msg instanceof BinaryMessage) {
                BinaryMessage bmsg = (BinaryMessage)msg;
                byte[] data = bmsg.getPayloadData();
                msgReceived = new String(data);
            }
        }
    }

    void send(String msg) {
        try {
            TextMessage tmsg = (TextMessage)serverConn.newMessage(MessageConnection.TEXT_MESSAGE);
        	tmsg.setAddress("sms://"+(new String(rs.getRecord(1))));
        	tmsg.setPayloadText(msg);
        	serverConn.send(tmsg);
		} catch (Exception exc) {
			exc.printStackTrace();
		}
    }

    void addToRS() {
        Vector recordsV = split(referralStr, '%');
        for (int i=0; i<recordsV.size(); i++) {
            try {
                data = recordsV.elementAt(i).toString().getBytes();
                rs.setRecord(i+4, data, 0, data.length);
            } catch(RecordStoreNotOpenException rsnoe) {
            } catch(RecordStoreException rse) {}
        }
        updateForms();

    }

    void updateForms() {
        try {
            referrerNameSI.setText(getData(4));
            referrerAdSI.setText(getData(5));
            referrerTelFaxSI.setText(getData(6));
            patientNameSI.setText(getData(7));
            ageSI.setText(getData(8));
            sexSI.setText(getData(9));
            patientAdSI.setText(getData(10));
            newPatientAdSI.setText(getData(11));
            caseNoSI.setText(getData(12));
            treatmentStartSI.setText(getData(13));
            categorySI.setText(getData(14));//
            classSI.setText(classesStr[Integer.parseInt(new String(rs.getRecord(15)))]);
            typeSI.setText(typesStr[Integer.parseInt(new String(rs.getRecord(16)))]);
            smearResultSI.setText(smearsStr[Integer.parseInt(new String(rs.getRecord(17)))]);
            for (int i=0; i<5; i++)
                drugsBitsStr[i] = getData(18+i);
            smearResultsStr = getData(23);
            for (int i=0; i<10; i++) {
                for (int j=0; j<5; j++)
                    if (drugsBitsStr[j].charAt(i) == '1')
                        drugsCG[i].setSelectedIndex(j, true);
                smearsSI[i].setText(String.valueOf(smearResultsStr.charAt(i)));
            }
            remarksSI.setText(getData(38));
            nameAndDesignationSI.setText(getData(39));
            dateReferredSI.setText(getData(40));
        } catch(RecordStoreNotOpenException rsnoe) {
        } catch (InvalidRecordIDException irie) {
        } catch (RecordStoreException rse) {}
    }

    Vector split(String s, char c)
    {
        Vector parts = new Vector();
        if ( s != null )
        {
            int lastfound = 0;
            int pos = 0;
            while ( (lastfound = s.indexOf(c,pos)) != - 1 )
            {
                parts.addElement(s.substring(pos,lastfound));
                pos = lastfound+1;
            }
            if ( pos <  s.length() ) parts.addElement(s.substring(pos));
        }

        return parts;
    }
    
    String getData(int id) {
        try {
            data = rs.getRecord(id);
        } catch(RecordStoreNotOpenException rsnoe) {
        } catch (InvalidRecordIDException irie) {
        } catch (RecordStoreException rse) {}
        catch (Exception e) {e.printStackTrace();}
        try {
            dataStr = new String(data);
            if (dataStr.equals("%"))
                return "";
            else
                return dataStr;
        } catch (Exception e) {e.printStackTrace();}
        return null;
    }

    class Timer extends Thread {
        public void run() {
            try {
                Thread.sleep(10000);
            } catch(InterruptedException ie) {}
            for (int i=0; i<referralSMSV.size(); i++)
            referralStr = referralStr.concat(referralSMSV.elementAt(i).toString());
        }
    }

    /*class Connection {

       void send(String msg) {
           

       }

       String receive() {


       }


    }*/

    /*private class LogoCanvas extends Canvas {
        public void paint(Graphics g) {
            try {
                logoImage = Image.createImage("/img/logo.png");
                g.drawImage(logoImage, getWidth()/2, getHeight()/2, Graphics.HCENTER);
            } catch (Exception e) {}
        }
    }*/
}
